package com.example.demo.cirtcl;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;

@RestController
@CrossOrigin // 允许跨域访问
public class FileUploadController {

    // 从配置文件中注入上传目录
//    @Value("${file.upload-dir:uploads}") // 默认值为uploads
    @Value("D:\\董建") // 默认值为uploads
    private String uploadDir;

    @PostMapping("/upload")
    public ResponseEntity<?> handleFileUpload(@RequestParam("file") MultipartFile file) {

        // 1. 检查文件是否为空
        if (file.isEmpty()) {
            return ResponseEntity.badRequest().body("请选择要上传的文件");
        }

        try {
            // 2. 创建上传目录（如果不存在）
            Path uploadPath = Paths.get(uploadDir);
            if (!Files.exists(uploadPath)) {
                Files.createDirectories(uploadPath);
            }

            // 3. 生成唯一文件名（防止覆盖）
            String originalFilename = file.getOriginalFilename();
            String extension = "文件2223";
//            if (originalFilename != null && originalFilename.contains(".")) {
//                extension = originalFilename.substring(originalFilename.lastIndexOf("."));
//            }
//            String uniqueFilename = UUID.randomUUID() + extension;
            String uniqueFilename = "文件2223";

            // 4. 保存文件
            Path filePath = uploadPath.resolve(uniqueFilename);
            file.transferTo(filePath.toFile());

            // 5. 构造返回结果
            return ResponseEntity.ok().body(
                    "文件上传成功\n"
                            + "- 原始文件名: " + originalFilename + "\n"
                            + "- 保存文件名: " + uniqueFilename + "\n"
                            + "- 文件大小: " + file.getSize() + " bytes\n"
                            + "- 存储路径: " + filePath.toString()
            );

        } catch (IOException e) {
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("文件上传失败: " + e.getMessage());
        } catch (Exception e) {
            return ResponseEntity.badRequest()
                    .body("上传错误: " + e.getMessage());
        }
    }
}